package com.wingsoft.homeFlow.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wingsoft.common.enums.SwitchEnum;
import com.wingsoft.common.exception.ServiceException;
import com.wingsoft.common.utils.SecurityUtils;
import com.wingsoft.common.utils.bean.BeanConvertUtils;
import com.wingsoft.homeFlow.bo.*;
import com.wingsoft.homeFlow.entity.HomeFlowTaskStep;
import com.wingsoft.homeFlow.entity.HomeFlowTaskVar;
import com.wingsoft.homeFlow.mapper.HomeFlowTaskVarMapper;
import com.wingsoft.homeFlow.service.HomeFlowTaskStepService;
import com.wingsoft.homeFlow.service.HomeFlowTaskVarService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Wingsoft
 * @description 针对表【HOME_FLOW_TASK_VAR(流水线任务参数)】的数据库操作Service实现
 * @createDate 2025-06-03 14:53:54
 */
@Service
public class HomeFlowTaskVarServiceImpl extends ServiceImpl<HomeFlowTaskVarMapper, HomeFlowTaskVar> implements HomeFlowTaskVarService {

    @Autowired
    private HomeFlowTaskStepService homeFlowTaskStepService;

    private final String reg = "^[A-Za-z][A-Za-z0-9]*$";
    private final String regDesc = "必须字母，或字母和数字组合，且必须以字母开头";

    @Transactional
    @Override
    public void add(HomeFlowTaskVarAddBo homeFlowTaskVarAddBo) {
        String taskCode = homeFlowTaskVarAddBo.getTaskCode();
        if (StringUtils.isBlank(taskCode)) {
            throw new ServiceException("任务编码 不能为空");
        }
        String stepCode = homeFlowTaskVarAddBo.getStepCode();
        if (StringUtils.isNotBlank(stepCode)) {
            if (!stepCode.matches(reg)) {
                throw new ServiceException("步骤KEY " + regDesc);
            }
            List<HomeFlowTaskStep> homeFlowTaskStepList = homeFlowTaskStepService.listByTaskCodeAndStepCode(taskCode, stepCode);
            if (ObjectUtils.isEmpty(homeFlowTaskStepList)) {
                throw new ServiceException("步骤数据不存在，请先保存步骤数据，然后再新增参数");
            }
        }
        String varCode = homeFlowTaskVarAddBo.getVarCode();
        if (StringUtils.isBlank(varCode)) {
            throw new ServiceException("参数key 不能为空");
        } else if (!varCode.matches(reg)) {
            throw new ServiceException("参数key " + regDesc);
        }
        Integer dataType = homeFlowTaskVarAddBo.getDataType();
        if (Objects.isNull(dataType)) {
            throw new ServiceException("数据类型 不能为空");
        } else {
            HomeFlowTaskVarBo.DataTypeEnum dataTypeEnum = HomeFlowTaskVarBo.DataTypeEnum.getEnumByCode(dataType);
            String defaultValue = homeFlowTaskVarAddBo.getDefaultValue();
            if (ObjectUtils.isNotEmpty(defaultValue)) {
                switch (dataTypeEnum) {
                    case SINGLE:
                        break;
                    case OBJECT:
                        try {
                            homeFlowTaskVarAddBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseObj(defaultValue)));
                        } catch (Exception e) {
                            throw new ServiceException("默认值 格式错误");
                        }
                        break;
                    case COLLECTION:
                        try {
                            homeFlowTaskVarAddBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseArray(defaultValue)));
                        } catch (Exception e) {
                            throw new ServiceException("默认值 格式错误");
                        }
                        break;
                }
            }
        }
        Integer globalFlag = homeFlowTaskVarAddBo.getGlobalFlag();
        if (Objects.isNull(globalFlag)) {
            throw new ServiceException("是否全局 不能为空");
        } else {
            SwitchEnum.getEnumByCode(globalFlag);
        }
        Integer flowFlag = homeFlowTaskVarAddBo.getFlowFlag();
        if (Objects.isNull(flowFlag)) {
            throw new ServiceException("是否流水线参数 不能为空");
        } else {
            SwitchEnum flowFlagEnum = SwitchEnum.getEnumByCode(flowFlag);
            switch (flowFlagEnum) {
                case FALSE:
                    if (ObjectUtils.isEmpty(stepCode)) {
                        throw new ServiceException("步骤KEY 不能为空");
                    }
                    break;
                case TRUE:
                    if (ObjectUtils.isNotEmpty(stepCode)) {
                        throw new ServiceException("步骤KEY 不能为空");
                    }
                    break;
            }
        }
        Integer manualFlag = homeFlowTaskVarAddBo.getManualFlag();
        if (Objects.isNull(manualFlag)) {
            throw new ServiceException("是否手动添加 不能为空");
        } else {
            SwitchEnum.getEnumByCode(manualFlag);
        }
        Integer varIndex = homeFlowTaskVarAddBo.getVarIndex();
        if (Objects.isNull(varIndex)) {
            homeFlowTaskVarAddBo.setVarIndex(0);
        }
        Integer isUsed = homeFlowTaskVarAddBo.getIsUsed();
        if (Objects.isNull(isUsed)) {
            homeFlowTaskVarAddBo.setIsUsed(SwitchEnum.TRUE.getCode());
        }
        List<HomeFlowTaskVar> list = this.list(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            if (StringUtils.isNotBlank(stepCode)) {
                eq(HomeFlowTaskVar::getStepCode, stepCode);
            } else {
                isNull(HomeFlowTaskVar::getStepCode);
            }
            eq(HomeFlowTaskVar::getVarCode, varCode);
        }});
        if (CollectionUtils.isNotEmpty(list)) {
            throw new ServiceException("变量编码 已存在");
        }
        Date date = new Date();
        Long userId = SecurityUtils.getUserId();
        if (!this.save(BeanConvertUtils.convert(homeFlowTaskVarAddBo, HomeFlowTaskVar.class, (s, t) -> {
            t.setCreateUserId(userId);
            t.setCreateTime(date);
            t.setUpdateUserId(userId);
            t.setUpdateTime(date);
        }))) {
            throw new ServiceException("新增失败");
        }
    }

    @Transactional
    @Override
    public void addNotManualList(List<HomeFlowTaskVarAddBo> homeFlowTaskVarAddBoList) {
        if (CollectionUtils.isEmpty(homeFlowTaskVarAddBoList)) {
            return;
        }
        if (homeFlowTaskVarAddBoList.stream().map(o -> o.getTaskCode() + o.getStepCode() + o.getVarCode()).distinct().count() != homeFlowTaskVarAddBoList.size()) {
            throw new ServiceException("变量编码 存在重复");
        }
        Date date = new Date();
        Long userId = SecurityUtils.getUserId();
        List<HomeFlowTaskVar> homeFlowTaskVarAddList = new ArrayList<>();
        List<HomeFlowTaskVar> homeFlowTaskVarList = this.listByTaskCodeList(homeFlowTaskVarAddBoList.stream().map(HomeFlowTaskVarAddBo::getTaskCode).collect(Collectors.toList()));
        for (HomeFlowTaskVarAddBo homeFlowTaskVarAddBo : homeFlowTaskVarAddBoList) {
            String taskCode = homeFlowTaskVarAddBo.getTaskCode();
            if (StringUtils.isBlank(taskCode)) {
                throw new ServiceException("任务编码 不能为空");
            }
            String stepCode = homeFlowTaskVarAddBo.getStepCode();
            if (StringUtils.isNotBlank(stepCode) && !stepCode.matches(reg)) {
                throw new ServiceException("步骤KEY " + regDesc);
            }
            String varCode = homeFlowTaskVarAddBo.getVarCode();
            if (StringUtils.isBlank(varCode)) {
                throw new ServiceException("参数字段名 不能为空");
            } else if (!varCode.matches(reg)) {
                throw new ServiceException("参数字段名 " + regDesc);
            }
            Integer dataType = homeFlowTaskVarAddBo.getDataType();
            if (Objects.isNull(dataType)) {
                throw new ServiceException("数据类型 不能为空");
            } else {
                HomeFlowTaskVarBo.DataTypeEnum dataTypeEnum = HomeFlowTaskVarBo.DataTypeEnum.getEnumByCode(dataType);
                String defaultValue = homeFlowTaskVarAddBo.getDefaultValue();
                if (ObjectUtils.isNotEmpty(defaultValue)) {
                    switch (dataTypeEnum) {
                        case SINGLE:
                            break;
                        case OBJECT:
                            try {
                                homeFlowTaskVarAddBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseObj(defaultValue)));
                            } catch (Exception e) {
                                throw new ServiceException("默认值 格式错误");
                            }
                            break;
                        case COLLECTION:
                            try {
                                homeFlowTaskVarAddBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseArray(defaultValue)));
                            } catch (Exception e) {
                                throw new ServiceException("默认值 格式错误");
                            }
                            break;
                    }
                }
            }
            Integer globalFlag = homeFlowTaskVarAddBo.getGlobalFlag();
            if (Objects.isNull(globalFlag)) {
                throw new ServiceException("是否全局 不能为空");
            } else {
                SwitchEnum.getEnumByCode(globalFlag);
            }
            Integer flowFlag = homeFlowTaskVarAddBo.getFlowFlag();
            if (Objects.isNull(flowFlag)) {
                throw new ServiceException("是否流水线参数 不能为空");
            } else {
                SwitchEnum flowFlagEnum = SwitchEnum.getEnumByCode(flowFlag);
                switch (flowFlagEnum) {
                    case FALSE:
                        if (ObjectUtils.isEmpty(stepCode)) {
                            throw new ServiceException("步骤KEY 不能为空");
                        }
                        break;
                    case TRUE:
                        if (ObjectUtils.isNotEmpty(stepCode)) {
                            throw new ServiceException("步骤KEY 不能为空");
                        }
                        break;
                }
            }
            Integer manualFlag = homeFlowTaskVarAddBo.getManualFlag();
            if (Objects.isNull(manualFlag)) {
                throw new ServiceException("是否手动添加 不能为空");
            } else {
                SwitchEnum.getEnumByCode(manualFlag);
            }
            Integer varIndex = homeFlowTaskVarAddBo.getVarIndex();
            if (Objects.isNull(varIndex)) {
                homeFlowTaskVarAddBo.setVarIndex(0);
            }
            Integer isUsed = homeFlowTaskVarAddBo.getIsUsed();
            if (Objects.isNull(isUsed)) {
                homeFlowTaskVarAddBo.setIsUsed(SwitchEnum.TRUE.getCode());
            }
            long count = homeFlowTaskVarList.stream()
                    .filter(o -> Objects.equals(o.getTaskCode(), taskCode))
                    .filter(o -> StringUtils.equals(o.getStepCode(), stepCode))
                    .filter(o -> StringUtils.equals(o.getVarCode(), varCode))
                    .count();
            if (count > 0L) {
                throw new ServiceException("变量编码 已存在");
            }
            homeFlowTaskVarAddList.add(BeanConvertUtils.convert(homeFlowTaskVarAddBo, HomeFlowTaskVar.class, (s, t) -> {
                t.setFlowFlag(SwitchEnum.FALSE.getCode());
                t.setManualFlag(SwitchEnum.FALSE.getCode());
                t.setCreateUserId(userId);
                t.setCreateTime(date);
                t.setUpdateUserId(userId);
                t.setUpdateTime(date);
            }));
        }
        if (CollectionUtils.isNotEmpty(homeFlowTaskVarAddList)) {
            if (!this.saveBatch(homeFlowTaskVarAddList)) {
                throw new ServiceException("新增失败");
            }
        }
    }

    @Transactional
    @Override
    public void uptStatusById(HomeFlowTaskVarUptBo homeFlowTaskVarUptBo) {
        String id = homeFlowTaskVarUptBo.getId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("ID 不能为空");
        }
        Integer isUsed = homeFlowTaskVarUptBo.getIsUsed();
        if (Objects.isNull(isUsed)) {
            throw new ServiceException("是否启用 不能为空");
        } else {
            SwitchEnum.getEnumByCode(isUsed);
        }
        Long userId = SecurityUtils.getUserId();
        if (!this.updateById(new HomeFlowTaskVar() {{
            setId(id);
            setIsUsed(isUsed);
            setUpdateUserId(userId);
            setUpdateTime(new Date());
        }})) {
            throw new ServiceException("修改失败");
        }
    }

    @Transactional
    @Override
    public void uptGlobalFlagById(HomeFlowTaskVarUptBo homeFlowTaskVarUptBo) {
        String id = homeFlowTaskVarUptBo.getId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("ID 不能为空");
        }
        Integer globalFlag = homeFlowTaskVarUptBo.getGlobalFlag();
        if (Objects.isNull(globalFlag)) {
            throw new ServiceException("是否全局 不能为空");
        } else {
            SwitchEnum.getEnumByCode(globalFlag);
        }
        Long userId = SecurityUtils.getUserId();
        if (!this.updateById(new HomeFlowTaskVar() {{
            setId(id);
            setGlobalFlag(globalFlag);
            setUpdateUserId(userId);
            setUpdateTime(new Date());
        }})) {
            throw new ServiceException("修改失败");
        }
    }

    @Transactional
    @Override
    public void uptById(HomeFlowTaskVarUptBo homeFlowTaskVarUptBo) {
        String id = homeFlowTaskVarUptBo.getId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("ID 不能为空");
        }
        HomeFlowTaskVar homeFlowTaskVar = this.getById(id);
        String taskCode = homeFlowTaskVar.getTaskCode();
        homeFlowTaskVarUptBo.setTaskCode(taskCode);
        String stepCode = homeFlowTaskVar.getStepCode();
        homeFlowTaskVarUptBo.setStepCode(stepCode);
        String varCode = homeFlowTaskVarUptBo.getVarCode();
        if (StringUtils.isBlank(varCode)) {
            throw new ServiceException("参数key 不能为空");
        } else if (!varCode.matches(reg)) {
            throw new ServiceException("参数key " + regDesc);
        }
        Integer dataType = homeFlowTaskVarUptBo.getDataType();
        if (Objects.isNull(dataType)) {
            throw new ServiceException("数据类型 不能为空");
        } else {
            HomeFlowTaskVarBo.DataTypeEnum dataTypeEnum = HomeFlowTaskVarBo.DataTypeEnum.getEnumByCode(dataType);
            String defaultValue = homeFlowTaskVarUptBo.getDefaultValue();
            if (ObjectUtils.isNotEmpty(defaultValue)) {
                switch (dataTypeEnum) {
                    case SINGLE:
                        break;
                    case OBJECT:
                        try {
                            homeFlowTaskVarUptBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseObj(defaultValue)));
                        } catch (Exception e) {
                            throw new ServiceException("默认值 格式错误");
                        }
                        break;
                    case COLLECTION:
                        try {
                            homeFlowTaskVarUptBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseArray(defaultValue)));
                        } catch (Exception e) {
                            throw new ServiceException("默认值 格式错误");
                        }
                        break;
                }
            }
        }
        Integer globalFlag = homeFlowTaskVarUptBo.getGlobalFlag();
        if (Objects.isNull(globalFlag)) {
            throw new ServiceException("是否全局 不能为空");
        } else {
            SwitchEnum.getEnumByCode(globalFlag);
        }
        Integer varIndex = homeFlowTaskVarUptBo.getVarIndex();
        if (Objects.isNull(varIndex)) {
            homeFlowTaskVarUptBo.setVarIndex(0);
        }
        Integer isUsed = homeFlowTaskVarUptBo.getIsUsed();
        if (Objects.nonNull(isUsed)) {
            SwitchEnum.getEnumByCode(isUsed);
        } else {
            homeFlowTaskVarUptBo.setIsUsed(SwitchEnum.TRUE.getCode());
        }
        List<HomeFlowTaskVar> list = this.list(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            if (StringUtils.isNotBlank(stepCode)) {
                eq(HomeFlowTaskVar::getStepCode, stepCode);
            } else {
                isNull(HomeFlowTaskVar::getStepCode);
            }
            eq(HomeFlowTaskVar::getVarCode, varCode);
            ne(HomeFlowTaskVar::getId, id);
        }});
        if (CollectionUtils.isNotEmpty(list)) {
            throw new ServiceException("变量编码 已存在");
        }
        Date date = new Date();
        Long userId = SecurityUtils.getUserId();
        if (!this.updateById(BeanConvertUtils.convert(homeFlowTaskVarUptBo, HomeFlowTaskVar.class, (s, t) -> {
            t.setUpdateUserId(userId);
            t.setUpdateTime(date);
        }))) {
            throw new ServiceException("修改失败");
        }
    }

    @Transactional
    @Override
    public void uptNotManualListById(String taskCode, String stepCode, List<HomeFlowTaskVarUptBo> homeFlowTaskVarUptBoList) {
        if (homeFlowTaskVarUptBoList.stream().map(o -> o.getTaskCode() + o.getStepCode() + o.getVarCode()).distinct().count() != homeFlowTaskVarUptBoList.size()) {
            throw new ServiceException("变量编码 存在重复");
        }
        this.remove(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            eq(HomeFlowTaskVar::getStepCode, stepCode);
            eq(HomeFlowTaskVar::getFlowFlag, SwitchEnum.FALSE.getCode());
            eq(HomeFlowTaskVar::getManualFlag, SwitchEnum.FALSE.getCode());
        }});
        if (CollectionUtils.isEmpty(homeFlowTaskVarUptBoList)) {
            return;
        }
        Date date = new Date();
        Long userId = SecurityUtils.getUserId();
        List<HomeFlowTaskVar> homeFlowTaskVarUptList = new ArrayList<>();
        List<HomeFlowTaskVar> homeFlowTaskVarList = this.listByTaskCode(taskCode);
        for (HomeFlowTaskVarUptBo homeFlowTaskVarUptBo : homeFlowTaskVarUptBoList) {
            homeFlowTaskVarUptBo.setTaskCode(taskCode);
            homeFlowTaskVarUptBo.setStepCode(stepCode);
            if (StringUtils.isBlank(taskCode)) {
                throw new ServiceException("任务编码 不能为空");
            }
            String stepCode1 = homeFlowTaskVarUptBo.getStepCode();
            if (StringUtils.isNotBlank(stepCode1) && !stepCode1.matches(reg)) {
                throw new ServiceException("步骤KEY " + regDesc);
            }
            String varCode = homeFlowTaskVarUptBo.getVarCode();
            if (StringUtils.isBlank(varCode)) {
                throw new ServiceException("参数字段名 不能为空");
            } else if (!varCode.matches(reg)) {
                throw new ServiceException("参数字段名 " + regDesc);
            }
            Integer dataType = homeFlowTaskVarUptBo.getDataType();
            if (Objects.isNull(dataType)) {
                throw new ServiceException("数据类型 不能为空");
            } else {
                HomeFlowTaskVarBo.DataTypeEnum dataTypeEnum = HomeFlowTaskVarBo.DataTypeEnum.getEnumByCode(dataType);
                String defaultValue = homeFlowTaskVarUptBo.getDefaultValue();
                if (ObjectUtils.isNotEmpty(defaultValue)) {
                    switch (dataTypeEnum) {
                        case SINGLE:
                            break;
                        case OBJECT:
                            try {
                                homeFlowTaskVarUptBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseObj(defaultValue)));
                            } catch (Exception e) {
                                throw new ServiceException("默认值 格式错误");
                            }
                            break;
                        case COLLECTION:
                            try {
                                homeFlowTaskVarUptBo.setDefaultValue(JSONUtil.toJsonStr(JSONUtil.parseArray(defaultValue)));
                            } catch (Exception e) {
                                throw new ServiceException("默认值 格式错误");
                            }
                            break;
                    }
                }
            }
            Integer globalFlag = homeFlowTaskVarUptBo.getGlobalFlag();
            if (Objects.isNull(globalFlag)) {
                throw new ServiceException("是否全局 不能为空");
            } else {
                SwitchEnum.getEnumByCode(globalFlag);
            }
            Integer varIndex = homeFlowTaskVarUptBo.getVarIndex();
            if (Objects.isNull(varIndex)) {
                homeFlowTaskVarUptBo.setVarIndex(0);
            }
            Integer isUsed = homeFlowTaskVarUptBo.getIsUsed();
            if (Objects.nonNull(isUsed)) {
                SwitchEnum.getEnumByCode(isUsed);
            } else {
                homeFlowTaskVarUptBo.setIsUsed(SwitchEnum.TRUE.getCode());
            }
            long count = homeFlowTaskVarList.stream()
                    .filter(o -> Objects.equals(o.getTaskCode(), taskCode))
                    .filter(o -> StringUtils.equals(o.getStepCode(), stepCode))
                    .filter(o -> StringUtils.equals(o.getVarCode(), varCode))
                    .count();
            if (count > 0L) {
                throw new ServiceException("变量编码 已存在");
            }
            homeFlowTaskVarUptList.add(
                    BeanConvertUtils.convert(homeFlowTaskVarUptBo, HomeFlowTaskVar.class, (s, t) -> {
                        t.setFlowFlag(SwitchEnum.FALSE.getCode());
                        t.setManualFlag(SwitchEnum.FALSE.getCode());
                        t.setUpdateUserId(userId);
                        t.setUpdateTime(date);
                    }));
        }
        if (CollectionUtils.isNotEmpty(homeFlowTaskVarUptList)) {
            if (!this.saveOrUpdateBatch(homeFlowTaskVarUptList)) {
                throw new ServiceException("修改失败");
            }
        }
    }

    @Transactional
    @Override
    public void delById(String id) {
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("ID 不能为空");
        }
        if (!this.removeById(id)) {
            throw new ServiceException("删除失败");
        }
    }

    @Override
    public Page<HomeFlowTaskVarVo> page(HomeFlowTaskVarQo homeFlowTaskVarQo) {
        LambdaQueryWrapper<HomeFlowTaskVar> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String id = homeFlowTaskVarQo.getId();
        if (StringUtils.isNotBlank(id)) {
            lambdaQueryWrapper.eq(HomeFlowTaskVar::getId, id);
        }
        String taskCode = homeFlowTaskVarQo.getTaskCode();
        if (StringUtils.isBlank(taskCode)) {
            throw new ServiceException("任务编码 不能为空");
        } else {
            lambdaQueryWrapper.eq(HomeFlowTaskVar::getTaskCode, taskCode);
        }
        String stepCode = homeFlowTaskVarQo.getStepCode();
        Integer flowFlag = homeFlowTaskVarQo.getFlowFlag();
        if (Objects.equals(flowFlag, SwitchEnum.TRUE.getCode())) {
            lambdaQueryWrapper.eq(HomeFlowTaskVar::getFlowFlag, SwitchEnum.TRUE.getCode());
        } else if (StringUtils.isNotBlank(stepCode)) {
            List<HomeFlowTaskStep> homeFlowTaskStepList = homeFlowTaskStepService.listByTaskCode(taskCode);
            Optional<HomeFlowTaskStep> first = homeFlowTaskStepList.stream().filter(o -> Objects.equals(o.getStepCode(), stepCode)).findFirst();
            if (first.isPresent()) {
                HomeFlowTaskStep homeFlowTaskStep = first.get();
                homeFlowTaskStepList = homeFlowTaskStepList.stream()
                        .filter(o -> o.getStepIndex() < homeFlowTaskStep.getStepIndex())
                        .collect(Collectors.toList());
            } else {
                throw new ServiceException("步骤KEY 不存在");
            }
            List<String> stepCodeList = homeFlowTaskStepList.stream().map(HomeFlowTaskStep::getStepCode).collect(Collectors.toList());
            lambdaQueryWrapper.and(la ->
                    la.in(CollectionUtils.isNotEmpty(stepCodeList), HomeFlowTaskVar::getStepCode, stepCodeList)
                            .or(la1 -> la1.eq(HomeFlowTaskVar::getFlowFlag, SwitchEnum.TRUE.getCode()))
                            .or(la1 -> la1.eq(HomeFlowTaskVar::getStepCode, stepCode).eq(HomeFlowTaskVar::getManualFlag, SwitchEnum.TRUE.getCode()))
            );
        }
        Integer globalFlag = homeFlowTaskVarQo.getGlobalFlag();
        if (Objects.nonNull(globalFlag)) {
            lambdaQueryWrapper.eq(HomeFlowTaskVar::getGlobalFlag, globalFlag);
        }
        Integer manualFlag = homeFlowTaskVarQo.getManualFlag();
        if (Objects.nonNull(manualFlag)) {
            lambdaQueryWrapper.eq(HomeFlowTaskVar::getManualFlag, manualFlag);
        }
        String varCode = homeFlowTaskVarQo.getVarCode();
        if (StringUtils.isNotBlank(varCode)) {
            lambdaQueryWrapper.eq(HomeFlowTaskVar::getVarCode, varCode);
        }
        String varName = homeFlowTaskVarQo.getVarName();
        if (StringUtils.isNotBlank(varName)) {
            lambdaQueryWrapper.like(HomeFlowTaskVar::getVarName, varName.trim());
        }
        lambdaQueryWrapper.eq(HomeFlowTaskVar::getGlobalFlag, SwitchEnum.TRUE.getCode());
        lambdaQueryWrapper.eq(HomeFlowTaskVar::getIsUsed, SwitchEnum.TRUE.getCode());
        int pageNum = homeFlowTaskVarQo.getPageNum();
        int pageSize = homeFlowTaskVarQo.getPageSize();
        lambdaQueryWrapper.orderByDesc(HomeFlowTaskVar::getFlowFlag);
        lambdaQueryWrapper.orderByAsc(HomeFlowTaskVar::getStepCode);
        lambdaQueryWrapper.orderByAsc(HomeFlowTaskVar::getVarIndex);
        lambdaQueryWrapper.orderByAsc(HomeFlowTaskVar::getCreateTime);
        lambdaQueryWrapper.orderByAsc(HomeFlowTaskVar::getId);
        Page<HomeFlowTaskVar> page = new Page<>(pageNum, pageSize);
        page.setOptimizeCountSql(false);
        Page<HomeFlowTaskVar> homeFlowTaskVarPage = this.page(page, lambdaQueryWrapper);
        return BeanConvertUtils.convert(homeFlowTaskVarPage, Page.class, (s, t) -> {
            t.setRecords(BeanConvertUtils.convertList(s.getRecords(), HomeFlowTaskVarVo.class));
        });

    }

    @Override
    public HomeFlowTaskVarVo getVoById(String id) {
        return BeanConvertUtils.convert(this.getById(id), HomeFlowTaskVarVo.class);
    }

    @Override
    public List<HomeFlowTaskVarVo> listVoByTaskCode(String taskCode) {
        List<HomeFlowTaskVar> homeFlowTaskVarList = this.listByTaskCode(taskCode);
        List<HomeFlowTaskVar> taskVarList = homeFlowTaskVarList.stream().filter(o -> Objects.equals(o.getIsUsed(), SwitchEnum.TRUE.getCode())).collect(Collectors.toList());
        return BeanConvertUtils.convertList(taskVarList, HomeFlowTaskVarVo.class);
    }

    @Override
    public List<HomeFlowTaskVar> listByTaskCode(String taskCode) {
        return this.list(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            orderByDesc(HomeFlowTaskVar::getCreateTime);
        }});
    }

    @Override
    public List<HomeFlowTaskVar> listByTaskCodeAndStepCode(String taskCode, String stepCode) {
        return this.list(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            eq(HomeFlowTaskVar::getStepCode, stepCode);
            orderByDesc(HomeFlowTaskVar::getCreateTime);
        }});
    }

    @Override
    public List<HomeFlowTaskVar> listByTaskCodeList(List<String> taskCodeList) {
        return this.list(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            in(HomeFlowTaskVar::getTaskCode, taskCodeList);
            orderByAsc(HomeFlowTaskVar::getTaskCode);
            orderByDesc(HomeFlowTaskVar::getCreateTime);
        }});
    }

    @Transactional
    @Override
    public void updateStepCode(String taskCode, String oldStepCode, String newStepCode) {
        if (!this.update(new LambdaUpdateWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            eq(HomeFlowTaskVar::getStepCode, oldStepCode);
            set(HomeFlowTaskVar::getStepCode, newStepCode);
        }})) {
            throw new ServiceException("更新失败");
        }
    }

    @Transactional
    @Override
    public void delByStepCode(String taskCode, String stepCode) {
        this.remove(new LambdaQueryWrapper<HomeFlowTaskVar>() {{
            eq(HomeFlowTaskVar::getTaskCode, taskCode);
            eq(HomeFlowTaskVar::getStepCode, stepCode);
        }});
    }

}




